package com.luyang.framework.validator.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import java.util.Set;

/**
 * 校验工具类
 *
 * @author lu_yang
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ValidatorUtil {

    /**
     * 校验工厂
     */
    private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 对象校验
     *
     * @param obj   待校验对象
     * @param clazz 待校验的组
     * @return void
     * @author lu_yang
     */
    public static void valid(Object obj, Class<?>... clazz) {
        valid(VALIDATOR.validate(obj, clazz));
    }

    /**
     * 指定属性校验
     *
     * @param obj       待校验对象
     * @param fieldName 指定属性
     * @param clazz     待校验的组
     * @return void
     * @author lu_yang
     */
    public static void valid(Object obj, String fieldName, Class<?>... clazz) {
        valid(VALIDATOR.validateProperty(obj, fieldName, clazz));
    }

    private static void valid(Set<ConstraintViolation<Object>> validate) {

        if (CollectionUtils.isEmpty(validate)) {
            return;
        }

        validate.forEach(v -> {
            throw new ValidationException(v.getPropertyPath() + ":" + v.getMessage());
        });
    }
}
